package org.example.corpus.corpuscenter.service.Impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.corpus.corpuscenter.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements RedisService {


    @Autowired
    private RedisTemplate<String, Object> jsonRedisTemplate;

    @Autowired
    private RedisTemplate<String, String> stringRedisTemplate;


    @Override
    public void setString(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }


    @Override
    public void setStringWithExpire(String key, String value, long timeout, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, value, timeout, unit);
    }


    @Override
    public void setJson(String key, Object value) {
        jsonRedisTemplate.opsForValue().set(key, value);
    }


    @Override
    public void setJsonWithExpire(String key, Object value, long timeout, TimeUnit unit) {
        jsonRedisTemplate.opsForValue().set(key, value, timeout, unit);
    }


    @Override
    public String getString(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }


    @Override
    public <T> T getJson(String key, Class<T> clazz) {
        Object value = jsonRedisTemplate.opsForValue().get(key);
        if (value == null) {
            return null;
        }
        // 使用 Jackson 或其他反序列化方法确保类型正确
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.convertValue(value, clazz);
}


    @Override
    public void deleteKey(String key) {
        jsonRedisTemplate.delete(key);
        stringRedisTemplate.delete(key);
    }


    @Override
    public boolean hasKey(String key) {
        return Boolean.TRUE.equals(jsonRedisTemplate.hasKey(key)) || Boolean.TRUE.equals(stringRedisTemplate.hasKey(key));
    }

    //刷新时间
    @Override
    public void refreshExpire(String key, long timeout, TimeUnit unit) {
        // 通过 RedisTemplate 刷新过期时间
        jsonRedisTemplate.expire(key, timeout, unit);
    }
}
